/**
 * UpAndDown.java
 * com.ebook.util
 * Copyright (c) 2013, 北京博观知翼有限公司版权所有.
*/

package com.ebook.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


/**
 * 上传下载通用组件
 * @author    潘吉友
 * @Date	 2013-3-8 	 
 */
public class UpAndDown {

	/**
	 * 文件下载功能
	 * @param filePath_Name  要下载的文件的路径	
	 * @param request   
	 * @param response
	 * @return true：成功，false：失败
	*/
	public static boolean downloadZip(String filePath_Name, HttpServletRequest request, HttpServletResponse response) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		System.out.println(filePath_Name);
		try {
			File file = new File(filePath_Name);
			if (!file.exists()) {
				System.out.println("file is not exists!");
				return false;
			}
			long fileLength = file.length();
			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=utf-8");
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				try {
					bis.close();
				} catch (IOException e) {
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
				}
		}

		// 走到这里说明下载失败
		return false;
	}
		
	/**
	 * 文件下载(断点续传)功能
	 * @param filePath_Name  要下载的文件的路径	
	 * @param request   
	 * @param response
	 * @return true：成功，false：失败
	*/
	public static void continueToDownload(String filePath_Name, HttpServletRequest request, HttpServletResponse response) {
		System.out.println("download address:"+filePath_Name);
		String range = request.getHeader("Range");
		try {
			File file = new File(filePath_Name);
			if (!file.exists()) {
				System.out.println("file is not exists!");
			}
			response.reset();
			response.setContentType("application/dmg");
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Content-Disposition", "attachment; filename="
					+ file.getName());
			response.setHeader("Content-Length", file.length() + "");
			OutputStream os = response.getOutputStream();
			System.out.println("range:"+range);
			FileInputStream fis = new FileInputStream(file);
			byte[] bytes = new byte[1024];
			if (range != null) {
				range = range.substring("bytes=".length(), range.length() - 1);
				long start = Long.parseLong(range);
				fis.skip(start);
				long l = file.length();
				String contentRange = new StringBuffer("bytes ").append(start)
						.append("-").append(l - 1).append("/").append(l)
						.toString();
				response.setHeader("Content-Range", contentRange);
				response
						.setHeader("Content-Length", file.length() - start + "");
				response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
			}
			BufferedInputStream bis = new BufferedInputStream(fis);
			int len = 0;
			while ((len = bis.read(bytes)) > 0) {
				os.write(bytes, 0, len);
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();	
				}
			}
			bis.close();
			os.flush();
			os.close();
		} catch (java.io.IOException e) {
			System.out.println("Interruption position:"+range);
		}
	}
}
